﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net;
using System.ServiceModel.DomainServices.Client;
using System.ServiceModel.DomainServices.Client.ApplicationServices;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using AppLab.Data.Resources;
using AppLab.Web;
using AppLab.Web.Services;

namespace AppLab.Views.Login
{
    public partial class PersonalSettings : ChildWindow
    {
        private IList<OperationBase> possiblyPendingOperations = new List<OperationBase>();
        private FlowContext flow = new FlowContext();
        private PersonalSetting personalSetting = new PersonalSetting();

        public PersonalSettings()
        {
            InitializeComponent();
            this.DataContext = personalSetting;
            this.NewDisplayNameTextBox.Text = WebContext.Current.User.DisplayName;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            personalSetting.UserName = WebContext.Current.User.Name;
            if (AdvanceValidateItem())
            {
                if ((bool)this.ChangedPasswordRadio.IsChecked)
                {
                    if (this.CustomDataForm.ValidateItem())
                    {
                        this.personalSetting.CurrentOperation = this.flow.UserChangedSetting(true, personalSetting, this.PersonalSettings_Completed, null);
                        this.possiblyPendingOperations.Add(this.personalSetting.CurrentOperation);
                        this.OKButton.IsEnabled = false;
                    }
                }
                else
                {
                    //暂时赋于值，不存入数据库；不予赋值，数据验证不过
                    personalSetting.OldPassword = "Password01!";
                    personalSetting.NewPassword = "Password02!";
                    personalSetting.ConfirmNewPassword = "Password02!";
                    personalSetting.Email = this.NewEamilTextBox.Text.Trim();
                    personalSetting.OldDisplayName = WebContext.Current.User.DisplayName;
                    personalSetting.NewDisplayName = this.NewDisplayNameTextBox.Text.Trim();
                    this.personalSetting.CurrentOperation = this.flow.UserChangedSetting(false, personalSetting, this.PersonalSettings_Completed, null);
                    this.possiblyPendingOperations.Add(personalSetting.CurrentOperation);
                    this.OKButton.IsEnabled = false;
                }
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void PersonalSettings_Completed(InvokeOperation<bool> operation)
        {
            if (!operation.IsCanceled)
            {
                if (operation.HasError)
                {
                    ErrorWindow.CreateNew(operation.Error);
                    operation.MarkErrorAsHandled();
                }
                else if (operation.Value)
                {
                    if ((bool)this.ChangedPasswordRadio.IsChecked)
                    {
                        MessageBox.Show("密码修改成功！");
                    }
                    else
                    {
                        MessageBox.Show("邮箱/显示名称更改成功！");
                    }
                    this.DialogResult = true;
                }
                else
                {
                    if ((bool)this.ChangedPasswordRadio.IsChecked)
                    {
                        MessageBox.Show("密码修改失败！");
                    }
                    else
                    {
                        MessageBox.Show("邮箱/显示名称更改失败！");
                    }
                }
            }
        }

        private void CustomDataForm_AutoGeneratingField(object sender, DataFormAutoGeneratingFieldEventArgs e)
        {
            // Put all the fields in adding mode
            e.Field.Mode = DataFieldMode.AddNew;

            if (e.PropertyName == "OldPassword")
            {
                PasswordBox passwordBox = (PasswordBox)e.Field.Content;
            }
            else if (e.PropertyName == "NewPassword")
            {
                PasswordBox passwordBox = (PasswordBox)e.Field.Content;
            }
            else if (e.PropertyName == "ConfirmNewPassword")
            {
                PasswordBox passwordBox = (PasswordBox)e.Field.Content;
            }
        }

        private void ChangedEmail_Checked(object sender, RoutedEventArgs e)
        {
            this.NewEamilTextBox.Text = "";
            this.TipForWorngEmail.Text = "";
        }

        private bool AdvanceValidateItem()
        {
            if ((bool)this.ChangedPasswordRadio.IsChecked)
            {
                // If either of the passwords has not yet been entered, then don't test for equality between
                // the fields.  The Required attribute will ensure a value has been entered for both fields.
                if (string.IsNullOrWhiteSpace(this.personalSetting.NewPassword)
                    || string.IsNullOrWhiteSpace(this.personalSetting.ConfirmNewPassword))
                {
                    return false;
                }
                // If the values are different, then add a validation error with both members specified
                if (this.personalSetting.NewPassword != this.personalSetting.ConfirmNewPassword)
                {
                    this.personalSetting.ValidationErrors.Add(new ValidationResult(
                            ValidationErrorResources.ValidationErrorPasswordConfirmationMismatch, new string[] { "NewPassword", "ConfirmNewPassword" }));
                    return false;
                }
            }
            else
            {
                if (this.NewDisplayNameTextBox.Text.Trim() == "")
                {
                    this.TipForWorngEmail.Text = "显示名称不允许为空！";
                    return false;
                }
                
                if (this.NewEamilTextBox.Text.Trim() == "")
                {
                    this.TipForWorngEmail.Text = "邮箱地址不允许为空！";
                    return false;
                }

                if (!Regex.IsMatch(this.NewEamilTextBox.Text.Trim(), @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"))
                {
                    this.TipForWorngEmail.Text = "无效邮件！";
                    return false;
                }
            }
            return true;
        }
    }
}

